package com.xl.ssh.intercepter;

import cn.hutool.core.util.StrUtil;
import com.xl.ssh.constants.Constants;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;

/**
 * 建立websocket连接前后的拦截器
 */
@Component
public class SSHWebSocketIntercepter implements HandshakeInterceptor {

    /**
     * 通过请求头中的token判断，请求是否合法
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        //检查亲请求头中是否包含鉴权信息
        if (request instanceof ServletServerHttpRequest) {
            HttpServletRequest req = ((ServletServerHttpRequest) request).getServletRequest();
            String authorizatiom = req.getHeader("Sec-WebSocket-Protocol");
            if (StrUtil.isBlank(authorizatiom)) {
                System.out.println("未知请求连接socket服务器,authorization:" + authorizatiom);
                return false;
            }
            //解析token的内容，将消息放到session里面 token格式：auth-userID
            //随机生成一个uuid
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String[] split = authorizatiom.split("-");
            attributes.put(Constants.USER_UUID_KEY, uuid);
            attributes.put(Constants.USER_INFO_KEY, split[1]);
            return true;
        } else {
            return false;
        }
    }

    /**
     *
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        if (request instanceof ServletServerHttpRequest) {
            HttpServletRequest req = ((ServletServerHttpRequest) request).getServletRequest();
            HttpServletResponse httpResponse = ((ServletServerHttpResponse) response).getServletResponse();
            if (StrUtil.isNotEmpty(req.getHeader("Sec-WebSocket-Protocol"))) {
                httpResponse.addHeader("Sec-WebSocket-Protocol", req.getHeader("Sec-WebSocket-Protocol"));
            }
        }
    }
}
